package com.sanjiahantang.youjiarole.module.me.account.views.impl;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.Html;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.sanjiahantang.plugin.pickerview.OptionsPickerView;
import com.sanjiahantang.uilibrary.popuwindow.SelectPhotoPopupwindow;
import com.sanjiahantang.uilibrary.utils.BitmapUtils;
import com.sanjiahantang.uilibrary.utils.PickerUtils;
import com.sanjiahantang.uilibrary.utils.Utils;
import com.sanjiahantang.uilibrary.views.CircleImageView;
import com.sanjiahantang.youjiarole.R;
import com.sanjiahantang.youjiarole.base.BaseBean;
import com.sanjiahantang.youjiarole.base.BaseMvpActivity;
import com.sanjiahantang.youjiarole.base.BaseView;
import com.sanjiahantang.youjiarole.config.ConfigValue;
import com.sanjiahantang.youjiarole.config.SPConfig;
import com.sanjiahantang.youjiarole.module.common.beans.ConditionBean;
import com.sanjiahantang.youjiarole.module.common.beans.FileBean;
import com.sanjiahantang.youjiarole.module.common.views.impl.LoveActivity;
import com.sanjiahantang.youjiarole.module.common.views.impl.SelectorActivity;
import com.sanjiahantang.youjiarole.module.join.views.impl.CertificationActivity;
import com.sanjiahantang.youjiarole.module.me.account.presenters.AccountPresenter;
import com.sanjiahantang.youjiarole.module.me.account.views.AccountView;
import com.sanjiahantang.youjiarole.utils.CheckUtil;
import com.sanjiahantang.youjiarole.utils.FileUtils;
import com.sanjiahantang.youjiarole.utils.KeyBoardUtils;
import com.sanjiahantang.youjiarole.utils.SPUtils;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import static com.sanjiahantang.youjiarole.module.common.views.SelectorView.KEY_INDEX;
import static com.sanjiahantang.youjiarole.module.decorate.views.DecorateManageView.INTENT_JOB;
import static com.sanjiahantang.youjiarole.module.decorate.views.DecorateManageView.INTENT_Love;

/**
 * Created by sks on 2015/9/16.
 * 我的资料
 */
public class AccountActivity extends BaseMvpActivity<AccountView, AccountPresenter>
        implements AccountView, View.OnClickListener {
    private Context context;
    private TextView title;
    private ImageView back;
    private View parentView;
    private String birthday;
    private int sex;
    private SelectPhotoPopupwindow photoPopupwindow;
    private OptionsPickerView pvOptions;
    private boolean pickerDataFlag = false;
    final int PHOTO_GRAPH = 2, SELECT_PICTURE = 3, INTENT_NICKNAME = 5, SAVE_PHOTO = 6;
    private static final int UPLOAD_PIC = 200;
    public static String filePath = "";
    private Uri imageUri;
    private String filedId;
    private View rlPhone, //手机号
            //rlUserName, //姓名
            rlGender, //性别
            rlJob, //职业
            rlLocation, //所在地
            rlInterest, //兴趣
            rlicon,
            fl_Left,
            rlQR; //我的二维码
    private TextView txtPhone, //手机号
            txtJuese,
            txtGender, //性别
            txtJob, //职业
            txtLocation, //所在地
            txtGHT//高汇通
            ; //兴趣
    EditText  txtUserName;//姓名
    private CircleImageView image_icon;
    private ArrayList<String> listProvince;
    private ArrayList<ArrayList<String>> listCity;
    private ArrayList<ArrayList<ArrayList<String>>> listArea;
    private ConditionBean.SelectorData jobData;
    private String hobbyKey,hobbyValue;
    private LinearLayout panelHobby;

    @Override
    public void initView() {
        setContentView(R.layout.activity_me_accout);
        context = this;

        title = (TextView) findViewById(R.id.title);
        title.setText("我的资料");
        txtJuese= (TextView) findViewById(R.id.txtJuese);
        rlPhone = findViewById(R.id.rlPhone);
        rlGender = findViewById(R.id.rlGender);
        rlJob = findViewById(R.id.rlJob);
        rlLocation = findViewById(R.id.rlLocation);
        rlInterest = findViewById(R.id.rlInterest);
        rlQR = findViewById(R.id.rlQR);
        rlicon=findViewById(R.id.rlicon);
        panelHobby = (LinearLayout) findViewById(R.id.panelHobby);
        panelHobby.setOnClickListener(this);

        rlicon.setOnClickListener(this);
        rlPhone.setOnClickListener(this);
        rlGender.setOnClickListener(this);
        rlJob.setOnClickListener(this);
        rlLocation.setOnClickListener(this);
        rlInterest.setOnClickListener(this);
        rlQR.setOnClickListener(this);
        txtPhone = (TextView) findViewById(R.id.txtPhone);
        txtUserName = (EditText) findViewById(R.id.txtUserName);
        txtGender = (TextView) findViewById(R.id.txtGender);
        txtJob = (TextView) findViewById(R.id.txtJob);
        txtLocation = (TextView) findViewById(R.id.txtLocation);
        txtGHT = (TextView) findViewById(R.id.txtGHT);
        image_icon = (CircleImageView) findViewById(R.id.image_icon);
        findViewById(R.id.fl_Left).setOnClickListener(this);
        parentView = findViewById(R.id.lineLayMain);
        photoPopupwindow = new SelectPhotoPopupwindow(context, this);
        findViewById(R.id.jue_se).setOnClickListener(this);
        String headUrl = ConfigValue.userInfo.getUrl();
        if(!TextUtils.isEmpty(headUrl)){
            Picasso.with(context).load(headUrl).placeholder(R.drawable.i_head_default).error(R.drawable.i_head_default).into(image_icon);
        }
        txtUserName.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                //event.getAction() == KeyEvent.ACTION_UP
                if (keyCode == KeyEvent.KEYCODE_ENTER) {

                    if (TextUtils.isEmpty(txtUserName.getText())){
                        Utils.showToast($this,"请填写昵称");
                        return true;
                    }

                    if (CheckUtil.isEmoji(txtUserName.getText().toString())){
                        Utils.showToast($this,"昵称存在非法字符");
                        return true;
                    }

                    presenter.setData(context, txtUserName.getText().toString(), "", "", txtJob.getText().toString(), txtLocation.getText().toString(), "", "", "name", new BaseView.OnLoadListener() {
                        @Override
                        public void onLoad(Object content) {
                            ConfigValue.userInfo.setUserName(txtUserName.getText().toString());
                            SPUtils.put(context, SPConfig.USERNAME, ConfigValue.userInfo.getUserName());
                        }
                    });
                    KeyBoardUtils.closeKeybord(txtUserName, $this);
                    return true;
                }
                return false;
            }
        });


        init();
        presenter.init(context);
    }

    @Override
    public void initData() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rlPhone:
                break;
            case R.id.jue_se:
                CheckUtil.getCurrentRoleId(context, new BaseView.OnLoadListener() {
                    @Override
                    public void onLoad(Object content) {
                        startActivity(new Intent($this, CertificationActivity.class));
                    }
                });

                break;
            case R.id.rlGender:
                PickerUtils.alertBottomWheelOption(context, presenter.getGenderList(), new PickerUtils.OnWheelViewClick() {
                    @Override
                    public void onClick(View view, int position) {
                        setGender(presenter.getGenderList().get(position));
                        presenter.setData(context, txtUserName.getText().toString(), "" + position, "", txtJob.getText().toString(), txtLocation.getText().toString(), "", "", "sex", new BaseView.OnLoadListener() {
                            @Override
                            public void onLoad(Object content) {

                            }
                        });
                    }
                });
                break;
            case R.id.rlJob://职业
                SelectorActivity.startActivity($this,ConfigValue.dutylist,"选择职业",jobData.getDicValue(),INTENT_JOB);
                break;
            case R.id.rlLocation:
                if (pickerDataFlag) {
                    pvOptions.show();
                }
                break;
            case R.id.panelHobby://喜爱
                Intent intent1 = new Intent(context, LoveActivity.class);
                Bundle c = new Bundle();
                c.putSerializable(KEY_PARAM, ConfigValue.favoritelist);
                intent1.putExtra(KEY_PARAM, c);
                intent1.putExtra(KEY_TITLE, "选择爱好");
                intent1.putExtra("isSelect",hobbyValue == null ? new String[]{}:hobbyValue.split(","));
                startActivityForResult(intent1, INTENT_Love);
                break;
            case R.id.rlQR:
                presenter.goPageQR(context);
                break;
            case R.id.fl_Left:
                finish();
                break;
            //拍照
            case R.id.btn_take_photo:
                photoPopupwindow.dismiss();
                if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        requestPermissions(new String[]{Manifest.permission.CAMERA}, 1);
                    }
                } else {
                    takePictures((Activity) context);
                   // presenter.takePictures((Activity) context);
                }
                break;
            //相册
            case R.id.btn_pick_photo:
                photoPopupwindow.dismiss();
                        cardSelect((Activity) context);
                break;
            case R.id.rlicon://头像
                photoPopupwindow.showAtLocation(rlicon, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                break;
        }
    }

    public void result(BaseBean model) {
        if (null != model && model.getCode() > 0) {
            if (model.getCode() == RESPONSE_CODE_SUC) {
            }
            Utils.showToast(context, model.getMessage());
        } else
            Utils.showToast(context, "提交失败");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        File file = new File("/sdcard/youjia/avatar/newhead.jpg");
        if (file.exists())
            file.delete();

    }

    @Override
    public AccountPresenter initPresenter() {
        return new AccountPresenter();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                takePictures((Activity) context);
            } else {
                Utils.showToast(this, "权限被禁止，相关功能无法使用！");
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    }

    @Override
    public void showProgress() {
        super.showProgress(context);
    }

    @Override
    public void setName(String name) {
        txtUserName.setText(name);
        txtUserName.setSelection(txtUserName.getText().toString().length());
    }

    @Override
    public void setGender(String gender) {
        txtGender.setText(gender);
    }

    @Override
    public void setPhone(String phone) {
        txtPhone.setText(phone);

    }

    @Override
    public void setJob(ConditionBean.SelectorData job) {
        jobData = job;
        if (job == null){
            txtJob.setText("未设置");
        }else{
            txtJob.setText(job.getDicName());
        }

    }

    @Override
    public void setLocate(String locate) {
        txtLocation.setText(locate);
        ConfigValue.userInfo.setAddress(locate);
    }

    @Override
    public void setRole(String role) {
        String b="";
        if (!TextUtils.isEmpty(role)){
            for (int i = 0;i < 4;i++){
                if (role.contains(String.valueOf(i))){
                    switch (i){
                        case 0:
                            b += "设计师、";
                            break;
                        case 1:
                            b += "项目经理、";
                            break;
                        case 2:
                            b += "监理、";
                            break;
                        case 3:
                            b += "体验店、";
                            break;
                    }
                }
            }
            b=b.substring(0,b.lastIndexOf("、"));
            txtJuese.setText(b);
        }else {
            txtJuese.setText("");
        }
    }

    @Override
    public void setGHTUserId(String ghtUserId) {
        txtGHT.setText(ghtUserId);
    }

    @Override
    public void setHobby(String hobbyCode,String hobbyName) {
        int d5 = Utils.dip2px(context,5);
        if (!TextUtils.isEmpty(hobbyCode)&&!TextUtils.isEmpty(hobbyName)){
            String [] hobby = hobbyName.split(",");
            hobbyKey = hobbyCode;
            hobbyValue = hobbyName;
            panelHobby.removeAllViews();
            for (int i = 0;i < hobby.length;i++){
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

                TextView textView = new TextView(context);
                textView.setBackgroundResource(R.drawable.x_shape_green_border);
                textView.setTextColor(COLOR_PRIMARY);
                textView.setTextSize(12);

                params.setMargins(d5,0,d5,0);
                textView.setPadding(d5 * 2,d5,d5 * 2,d5);
                textView.setText(hobby[i]);
                textView.setLayoutParams(params);
                panelHobby.addView(textView);
            }
        }else{
            panelHobby.removeAllViews();
            TextView textView = new TextView(context);
            textView.setTextColor(Color.rgb(0x90,0x90,0x90));
            textView.setTextSize(14);
            textView.setPadding(0,0,0,d5);
            textView.setText("未设置");
            panelHobby.addView(textView);
        }

    }

    @Override
    public void setImage(String url,String id) {
        if (id==null){
            filedId="0";
        }else {
            filedId=id;
        }

        Picasso.with($this).load(FileUtils.rePath(url)).into(image_icon);
        ConfigValue.userInfo.setFileId(filedId);
        ConfigValue.userInfo.setUrl(url);

    }

    public void init() {
        presenter.loadPersonCityList($this, new BaseView.OnLoadListener() {
            @Override
            public void onLoad(Object content) {
                Object[] listArray = (Object[]) content;
                listProvince = (ArrayList<String>) listArray[0];
                listCity = (ArrayList<ArrayList<String>>) listArray[1];
                listArea = (ArrayList<ArrayList<ArrayList<String>>>) listArray[2];
                pvOptions = new OptionsPickerView.Builder($this, new OptionsPickerView.OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        //返回的分别是三个级别的选中位置
                        final String tx = listProvince.get(options1) + " " +
                                listCity.get(options1).get(options2) + " " +
                                listArea.get(options1).get(options2).get(options3);
                        txtLocation.setText(tx);
                        presenter.setData(context, txtUserName.getText().toString(), "", "", "", txtLocation.getText().toString(), "", "", "address", new BaseView.OnLoadListener() {
                            @Override
                            public void onLoad(Object content) {
                                ConfigValue.userInfo.setAddress(tx);
                            }
                        });

                    }
                })

                        .setTitleText("")
                        .setDividerColor(Color.BLACK)
                        .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                        .setContentTextSize(20)
                        .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
           pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
                pvOptions.setPicker(listProvince, listCity, listArea);//三级选择器
                pickerDataFlag = true;
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode != Activity.RESULT_OK) {
            switch (requestCode) {
                case INTENT_JOB:
                    if (data != null) {
                        jobData = (ConditionBean.SelectorData) data.getSerializableExtra(KEY_PARAM);
                        if (jobData != null) {
                            txtJob.setText(jobData.getDicName());
                            presenter.setData(context, txtUserName.getText().toString(), "", jobData.getDicCode(), txtJob.getText().toString(), txtLocation.getText().toString(), "", "", "job", new BaseView.OnLoadListener() {
                                @Override
                                public void onLoad(Object content) {

                                }
                            });
                        }
                    }
                    break;
                case INTENT_Love:
                    if (data != null) {
                        String value = data.getStringExtra("favoriteValue");
                        String key = data.getStringExtra("favoriteKey");
                        setHobby(key,value);
                        presenter.setData(context, "", "", "", "", "", key, value, "like", new BaseView.OnLoadListener() {
                            @Override
                            public void onLoad(Object content) {

                            }
                        });
                    }
                    break;

//                case PHOTO_GRAPH:
//                    startImageAction(context, imageUri, 320, 320,
//                            SAVE_PHOTO, true);
//                    break;
                case SELECT_PICTURE:
                    startImageAction(context, data.getData(), 320, 320,
                            SAVE_PHOTO, true);
                    break;
                case SAVE_PHOTO:

                    if (data == null)
                        return;
                    else
                        Utils.showToast(context, "保存");
                    showPhoto(context, data);
                    filePath = "";
                    break;
                case UPLOAD_PIC:
                    Uri uri = data.getData();
                    presenter.doUpload(context, uri, new BaseView.OnLoadListener() {
                        @Override
                        public void onLoad(Object content) {
                            if (content != null && content instanceof FileBean.Data){
                                FileBean.Data data = (FileBean.Data) content;
                                ConfigValue.userInfo.setUrl(data.getUrl());
                                if (data.getMallId() > 0){
                                    ConfigValue.userInfo.setFileId(String.valueOf(data.getMallId()));
                                }

                                Picasso.with(context).load(FileUtils.rePath(data.getUrl()))
                                        .placeholder(R.drawable.i_rect_bg)
                                        .into(image_icon);
                            }
                        }
                    });
                    break;
                case PHOTO_GRAPH:
                    if (data != null){
                        Bundle b = data.getExtras();
                        Bitmap bitmap = (Bitmap) b.get("data");
                        bitmap = BitmapUtils.resizeBitmap(bitmap, 480);
                        image_icon.setImageBitmap(bitmap);
                        presenter.doUpload(context, bitmap, new BaseView.OnLoadListener() {
                            @Override
                            public void onLoad(Object content) {
                                if (content != null && content instanceof FileBean.Data){
                                    FileBean.Data data = (FileBean.Data) content;
                                    ConfigValue.userInfo.setUrl(data.getUrl());
                                    Picasso.with(context).load(FileUtils.rePath(data.getUrl()))
                                            .placeholder(R.drawable.i_rect_bg)
                                            .into(image_icon);
                                }
                            }
                        });
                    }else{
                        Utils.showToast(context,"请从相册选择图片");
                    }
                    break;
            }
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    //相机拍照获取图片
    public void takePictures(Activity activity) {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            File dir = new File("/sdcard/youjia/avatar/");
            Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File file = new File(dir, "newhead.jpg");
            try{
//                Uri photoUri = FileProvider.getUriForFile(
//                        activity,
//                        activity.getPackageName() + ".provider",
//                        file);
//                takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);

//                filePath = file.getAbsolutePath();
                imageUri = Uri.fromFile(file);

                activity.startActivityForResult(takePhotoIntent, PHOTO_GRAPH);
            }catch (Exception e){
                e.printStackTrace();
                Utils.showToast(context,"请从相册上传图片");
            }


        } else
            Toast.makeText(activity, "未插入SD卡", Toast.LENGTH_SHORT).show();
    }
    public void cardSelect(Activity activity) {
        Intent it = new Intent(Intent.ACTION_PICK);
        it.setType("image/*");
        activity.startActivityForResult(it, UPLOAD_PIC);
    }

    private void showPhoto(Context context,Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            Bitmap bitmap = extras.getParcelable("data");
            if (bitmap != null) {
                image_icon.setImageBitmap(bitmap);
                presenter.doUpload(context, bitmap,filedId);
                if (bitmap != null && bitmap.isRecycled()) {
                    bitmap.recycle();
                }
            }
        } else if (data.getData() != null) {
            Uri uri = data.getData();
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), uri);
                if (bitmap != null && bitmap.isRecycled()) {
                    bitmap.recycle();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * 剪裁照片，并将剪裁之后的照片存在imageUri中，照片的名称问newhead.jpg,若提交更改，则将newhead.jpg重命名为head.jpg
     *
     * @param uri
     * @param outputX
     * @param outputY
     * @param requestCode
     * @param isCrop
     */
    private void startImageAction(Context context, Uri uri, int outputX, int outputY,
                                  int requestCode, boolean isCrop) {

        Intent intent = null;
        if (isCrop) {
            intent = new Intent("com.android.camera.action.CROP");
        } else {
            intent = new Intent(Intent.ACTION_GET_CONTENT, null);
        }
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            File file = new File(Environment.getDownloadCacheDirectory() + "/" + (new File(uri.getPath())).getName());

            intent.setDataAndType(uri, "image/*");
            intent.putExtra("crop", "true");
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            intent.putExtra("outputX", outputX);
            intent.putExtra("outputY", outputY);
            intent.putExtra("scale", true);
            intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
            intent.putExtra("return-data", true);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//这里加入flag
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.putExtra("noFaceDetection", true); // no face detection
            ((Activity)context).startActivityForResult(intent, requestCode);
        }

    }
    @Override
    public void onBackPressed() {
        if (pvOptions != null && pvOptions.isShowing()) {
            pvOptions.dismiss();
            return;
        }
        super.onBackPressed();
    }

}
